package com.webull.information.center.carwler.task.handler;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.webull.information.center.carwler.common.model.NewsInformation;
import com.webull.information.center.carwler.common.model.StockConfig;
import com.webull.information.center.carwler.common.model.StockTitle;
import com.webull.information.center.carwler.common.util.jsoup.HttpJsoupClient;
import com.webull.information.center.carwler.common.util.news.SinaNewsListUitl;
import com.webull.information.center.carwler.common.util.news.SinaNewsListUitl.SinaItem;
import com.webull.information.center.carwler.task.support.StockConfigSupport;
import com.webull.information.center.carwler.task.support.TikcerNewsProcessor;
import com.webull.information.center.common.constants.Constants;
import com.webull.information.center.common.constants.UrlConstants;
import com.webull.information.client.model.News;
import com.webull.information.client.model.parm.NewsRelType;

/**
 * 新浪新闻处理
 * 
 * @author shimingjun
 * @date 2016年8月26日 下午4:06:09
 * @version 1.0
 * @since JDK 1.8
 */
@Component
public class StockSinaCnNewsHandler {

	protected final Logger logger = LogManager.getLogger(getClass());
	private static String sina_lang = Constants.lang_zh;// 新浪语言版本
	private @Autowired SinaNewsListUitl sinaNewsListUitl;
	private @Autowired StockConfigSupport stockConfigSupport;
	private @Autowired TikcerNewsProcessor tikcerNewsProcessor;



	public void handlerByStockTitle4SinaCn(StockTitle stockTitle) {
		String symbol = stockTitle.getSymbol();
		StockConfig stockConfig = stockConfigSupport.getStockConfig(stockTitle, "sina_cn", sina_lang);
		String newsProfile = getSinaProfileUrl(stockTitle.getRegionId(), stockTitle.getExchangeCode(), symbol);
		processSinaList(stockConfig, stockTitle, newsProfile);
	}

	private void processSinaList(StockConfig stockConfig, StockTitle stockTitle, String newsProfile) {
		try {
			List<Date> times = new ArrayList<>();
			Date lastPush = stockConfig.getCollectTime();
			/**
			 * 获取标的物新闻首页列表
			 */
			List<SinaItem> newsList = sinaNewsListUitl.parseNewsList(newsProfile, stockTitle.getRegionId());
			//
			entrie: for (int i = 0; newsList != null && i < newsList.size(); i++) {
				try {
					SinaItem item = newsList.get(i);
					Date push = item.getNewsTime();
					if (push == null) {
						logger.warn("-processSinaList stockTitle:{}, url:{} SinaItem:{}, push can't be parse!!",
								stockTitle, newsProfile, item);
						continue entrie;
					}

					if (lastPush == null || push.after(lastPush)) {
						times.add(push);
						processSinaNews(stockTitle, item);
					}
				} catch (Exception e) {
					logger.warn("processSinaList errr:", e);
					break entrie;
				}
			}

			if (!times.isEmpty()) {
				tikcerNewsProcessor.updateStockConfig(stockConfig,times);
				stockConfigSupport.updateById(stockConfig);
			}

		} catch (Exception e) {
			logger.error("processSinaList", e);
		}
	}

	private void processSinaNews(StockTitle stockTitle, SinaItem item) throws Exception {
		String title = item.getTitle();
		String link = item.getLink();
		// SyndContent description = entry.getDescription();
		NewsInformation info = new NewsInformation();// produce(doc);

		info.setTitle(title);
		info.setRegionId(stockTitle.getRegionId());
		// String summary = description.getValue();
		// Document summaryDoc = Jsoup.parse(summary);

		// info.setSourceName(summaryDoc.getElementsByTag("span").get(0).html());
		// info.setPushTime(summaryDoc.getElementsByTag("span").get(1).html());
		info.setNewsTime(item.getNewsTime());
		// info.setSummary(StringUtils.substring(summaryDoc.select("div[style~=width:80%]").first().html(),
		// 0, 200));
		info.setUrl(link);
		info.setLanguage(sina_lang);
		info.setCollectSource(News.CollectSource.sinaCn);
		String md5 = HttpJsoupClient.finishingMd5Url(link);
		info.setUrlMd5(md5);

		tikcerNewsProcessor.bindTargetNewsRecord(info, stockTitle.getTickerId(), NewsRelType.ticker);
	}

	/**
	 * 转换成新浪个股资讯首页
	 * @param regionId
	 * @param exchange
	 * @param symbol
	 * @return
	 */
	private String getSinaProfileUrl(Integer regionId, String exchange, String symbol) {
		// map.put("SHH", "sh");// 上海
		// map.put("SHZ", "sz");// 深圳
		if (Integer.valueOf(1).equals(regionId)) {
			String sina_exchange = "SHH".equalsIgnoreCase(exchange) ? "sh" : "sz";
			return StringUtils.replaceOnce(UrlConstants.sinaCnNewsUnitUrl, "{symbol}", sina_exchange + symbol);
		} else if (Integer.valueOf(2).equals(regionId)) {// 港股5位代码
			return StringUtils.replaceOnce(UrlConstants.sinaHKNewsUnitUrl, "{symbol}",
					StringUtils.leftPad(symbol, 5, '0'));
		} else if (Integer.valueOf(6).equals(regionId)) {
			return StringUtils.replaceOnce(UrlConstants.sinaUSNewsUnitUrl, "{symbol}", symbol);
		}
		return null;
	}

}
